#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
WebSocket会话管理器
管理ASR和TTS会话的生命周期
"""

import asyncio
import time
from core import extensions


def cleanup_asr_session(client_id):
    """
    清理流式ASR会话
    
    Args:
        client_id: 客户端ID
    """
    print(f"🧹 清理流式ASR会话: {client_id}")
    
    try:
        # 清理streaming_sessions
        if client_id in extensions.streaming_sessions:
            session = extensions.streaming_sessions[client_id]
            
            if 'task' in session and session['task']:
                session['task'].cancel()
            
            if 'asr_service' in session and session['asr_service']:
                loop = session.get('loop')
                if loop and not loop.is_closed():
                    asyncio.run_coroutine_threadsafe(
                        session['asr_service'].disconnect(),
                        loop
                    )
            
            del extensions.streaming_sessions[client_id]
        
        # 清理streaming_audio_buffer
        if client_id in extensions.streaming_audio_buffer:
            del extensions.streaming_audio_buffer[client_id]
        
        # 清理streaming_audio_queues
        if client_id in extensions.streaming_audio_queues:
            del extensions.streaming_audio_queues[client_id]
            
        print(f"✅ ASR会话清理完成: {client_id}")
        
    except Exception as e:
        print(f"❌ 清理流式ASR会话失败: {e}")


def cleanup_tts_session(client_id):
    """
    清理流式TTS会话
    
    Args:
        client_id: 客户端ID
    """
    print(f"🧹 清理流式TTS会话: {client_id}")
    
    try:
        if client_id in extensions.tts_sessions:
            session = extensions.tts_sessions[client_id]
            
            if 'task' in session and session['task']:
                session['task'].cancel()
            
            if 'tts_service' in session and session['tts_service']:
                loop = session.get('loop')
                if loop and not loop.is_closed():
                    asyncio.run_coroutine_threadsafe(
                        session['tts_service'].disconnect(),
                        loop
                    )
            
            del extensions.tts_sessions[client_id]
            print(f"✅ TTS会话清理完成: {client_id}")
            
    except Exception as e:
        print(f"❌ 清理流式TTS会话失败: {e}")


def cleanup_client_sessions(client_id):
    """
    清理客户端的所有会话（ASR和TTS）
    
    Args:
        client_id: 客户端ID
    """
    cleanup_asr_session(client_id)
    cleanup_tts_session(client_id)
    
    # 移除连接客户端
    extensions.connected_clients.discard(client_id)

